package com.andong.service.impl;

import com.andong.domain.dto.AdminAuthDTO;
import com.andong.domain.pojo.Result;
import com.andong.domain.vo.AdminAuthVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.andong.domain.entity.AdminAuth;
import com.andong.service.AdminAuthService;
import com.andong.mapper.AdminAuthMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.andong.utils.SystemConstant.*;

/**
* @author 王海云
* @description 针对表【admin_auth(管理员权限表)】的数据库操作Service实现
* @createDate 2024-01-16 20:49:23
*/
@Service
public class AdminAuthServiceImpl extends ServiceImpl<AdminAuthMapper, AdminAuth>
    implements AdminAuthService{

    @Resource
    private AdminAuthMapper adminAuthMapper;
    @Resource
    private RedisTemplate<String, List<String>> redisTemplate;
    @Override
    public List<AdminAuthVO> getAuthById(Long id) {
        List<AdminAuthVO> adminAuthVOS = adminAuthMapper.getAuthById(id);
        // 存入redis
        List<String> auths = new ArrayList<>();
        for (AdminAuthVO adminAuthVO : adminAuthVOS) {
            auths.add(adminAuthVO.getName());
        }
        redisTemplate.opsForValue().set(ADMIN_AUTH + id, auths, ADMIN_AUTH_EXPIRE, TimeUnit.MINUTES);
        return adminAuthVOS;
    }

    @Override
    @Transactional
    public Result saveOrModify(AdminAuthDTO dto) {
        // 删除之后，插入之前要考虑别的线程有没有在获取权限 解决办法(添加事物，原子性 一致性)
        // 1.先删除原来的权限信息
        lambdaUpdate()
                .eq(AdminAuth::getAdminId, dto.getAdminId())
                .remove();
        List<Long> authIds = dto.getAuthIds();
        // 2. 插入新权限信息
        for (Long authId : authIds) {
            AdminAuth adminAuth = AdminAuth.builder()
                    .adminId(dto.getAdminId())
                    .authId(authId)
                    .build();
            save(adminAuth);
        }
        redisTemplate.delete(ADMIN_AUTH + dto.getAdminId());
        return Result.success();
    }
}




